package com.rrd.itext.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class ViewTemplatesServlet extends HttpServlet {
    
    private static final long serialVersionUID = 1L;
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = null;
        try {
            out = response.getWriter(); 
        } catch (IOException e1) {
            e1.printStackTrace();
        }
       
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024 * 1024);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(1024 * 1024 * 50);
        upload.setHeaderEncoding("utf-8");
        upload.setSizeMax(1024 * 1024 * 100);

        List<FileItem> list = null;
        try {
            list = upload.parseRequest(request);
        } catch (FileUploadException e) {
            out.print("Faild to parse the files");
            e.printStackTrace();
            return;
        }

        if (!ServletFileUpload.isMultipartContent(request)) {
            out.print("Only support multipart/form-data");
            return;
        }
        Iterator<FileItem> it = list.iterator();
        while (it.hasNext()) {
            FileItem fi = (FileItem) it.next();

            if (fi.isFormField()) {
                String name = fi.getFieldName();
                String content = null;
                try {
                    content = fi.getString("utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                if("templateName".equals(name)){
                    String templateName = new String(content);
                    request.setAttribute(name, templateName);
                    break;
                }
            }
        }
        it = list.iterator();
        while (it.hasNext()) {
            FileItem fi = (FileItem) it.next();
            if (!fi.isFormField()) {
                try {
                    String pathStr = fi.getName();
                    if (pathStr.trim().equals("")) {
                        continue;
                    }
                    String name = fi.getFieldName();
                    InputStream in = fi.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(in));
                    if("dataXmlFile".equals(name)){
                        StringBuffer buffer = new StringBuffer();
                        String line = "";
                        while ((line = br.readLine()) != null){
                          buffer.append(line);
                        } 
                        request.setAttribute(name, buffer.toString());
                    }
                } catch (Exception e) {
                    out.print("Failed to upload the files");
                    e.printStackTrace();
                    return;
                } finally {
                    fi.delete();
                }
            }
        }
        ServletContext sc = getServletContext();
        RequestDispatcher rd = sc.getRequestDispatcher("/SamplePDF");
        rd.forward(request, response);
    }
    
    private String getTemporaryName(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String time = sdf.format(new Date());
        int random = (int)(Math.random()*1000000);
        return time + "-" + random;
    }
}
